package com.zl.learning.lambada;

import com.zl.learning.lambada.model.ClassRoom;
import com.zl.learning.lambada.model.User;
import org.junit.Test;

import java.util.Optional;

public class OptionalTest {

    @Test
    public void test1() {
        User user = new User();
        user.setUsername("zhangsan");
        user.setPassword("123456");
        Optional.of(user).ifPresent(r -> System.out.println(r.getUsername()));
    }

    @Test
    public void test2() {
        User user = null;
        Optional.ofNullable(user).ifPresent(r -> System.out.println(r.getUsername()));
    }

    @Test
    public void test3() {
        User user = new User();
        ClassRoom classRoom = new ClassRoom();
        classRoom.setClassName("bbbb");
        user.setClassRoom(classRoom);
        Optional.ofNullable(user).flatMap(r -> Optional.ofNullable(r.getClassRoom())).ifPresent(r -> System.out.println(r.getClassName()));
    }

    @Test
    public void test4() {
        User user = new User();
        ClassRoom classRoom = new ClassRoom();
        classRoom.setClassName("bbbb");
//        user.setClassRoom(classRoom);
        ClassRoom classRoom1 = Optional.ofNullable(user).flatMap(r -> Optional.ofNullable(r.getClassRoom())).orElseGet(ClassRoom::new);
        System.out.println(classRoom1.getClassName());
    }

    @Test
    public void test5() {
        User user = new User();
        ClassRoom classRoom = new ClassRoom();
        classRoom.setClassName("bbbb");
        user.setClassRoom(classRoom);
        if (user.getClassRoom() != null && "bbbb".equals(user.getClassRoom().getClassName())) {
            System.out.println(user.getClassRoom().getClassName());
        }
//        Optional.ofNullable(user).flatMap(r->Optional.ofNullable(r.getClassRoom())).filter(r->r.getClassName().equals("bbbb")).ifPresent(r-> System.out.println(r.getClassName()));
        Optional.of(user).flatMap(r -> Optional.ofNullable(r.getClassRoom())).filter(r -> "babb".equals(r.getClassName())).map(ClassRoom::getClassName).ifPresent(System.out::print);
    }


}
